import Util from '@/common/libs/util';
import Cookies from 'js-cookie';
import process from "@/common/libs/process"
import md5 from "md5"
import Vue from "vue"

export default function(vm) {
	// ***用于异步请求*************************************************************************************
	function ajax(method, url, data, callback, config) {
		data = data || {};
		data = JSON.parse(JSON.stringify(data));
		data.token = localStorage.token || ""; // 设置token
		for(var key in data) {
			if(data[key] != null && data[key] instanceof Object) data[key] = JSON.stringify(data[key]);
		}
		
		config = config || {};

		if(config.cache) {
			var hash = md5(url+JSON.stringify(data));
			var apiCacheData = getApiCacheData(hash);
			if(apiCacheData) {
				cb(apiCacheData);
			}else {
				vm.$http[method](url, data).then(function(res) {
					addApiCacheData(hash, { body: res.body });
					cb(res);
				});
			}
		}else {
			vm.$http[method](url, data).then(cb);
		}
		
		function cb(res) {
			if(res.body.status == 10000) {
				callback(res.body);
			}else if(res.body.status == 10611) { // 未登录或session失效
				alert(res.body.message);
				vm.$store.commit("logout", vm);
				vm.$router.push({ name: 'login' });
			}else {
				var error_str = `请求错误，错误码：${res.body.status},错误信息：${res.body.message}`;
				console.log(error_str);
				vm.$CustomMessage.error(error_str);
			}
		}
	}
	Vue.prototype.api = {
		api_url: "/api/",
		get: function(url, data, callback, config) {
			ajax("get", this.api_url+url, data, callback, config);
		},
		post: function(url, data, callback, config) {
			if(typeof(data) == "function") {
				config = callback;
				callback = data;
				data = null;
			}
			ajax("post", this.api_url+url, data, callback, config);
		},
		getResource: function(url, data, callback) {
			if(typeof(data) == "function") {
				callback = data;
				data = null;
			}
			data = data || {};
			data = JSON.parse(JSON.stringify(data));
			data.token = localStorage.token || ""; // 设置token
			for(var key in data) {
				if(data[key] != null && data[key] instanceof Object) data[key] = JSON.stringify(data[key]);
			}
			window.open(generateURLWithParams(this.api_url+url, data));
			if(callback) callback();
		}
	}
	function generateURLWithParams(url, data) {
        return url + "?" + generateURLParams(data);
    }
    function generateURLParams(data) {
		if(!data) return "";
        var arr = new Array();
        var i = 0;
        for(var attr in data) {
            arr[i] = encodeURIComponent(attr) + "=" + encodeURIComponent(data[attr]);
            i++;
        }
        return arr.join("&");
    }

	// ***消息提示*************************************************************************************
	Vue.prototype.$CustomMessage = {
		info: function(message) {
			vm.$Modal.info({
				content: message
			});
		},
		success: function(message) {
			vm.$Modal.success({
				content: message
			});
		},
		warning: function(message) {
			vm.$Modal.warning({
				content: message
			});
		},
		error: function(message) {
			vm.$Modal.error({
				content: message
			});
		},
		confirm: function(message) {
			vm.$Modal.confirm({
				content: message
			});
		}
	}

	// ***用于缓存组件时候使用*************************************************************************************
	var url_map = {
		// url_name: { new_path: fullPath, old_path: fullPath }
	};

	vm.$watch("$route", route => {
		if(!url_map[route.name]) {
			url_map[route.name] = { new_path: "", old_path: "" };
		}
		var temp = url_map[route.name];
		temp.old_path = temp.new_path;
		temp.new_path = route.fullPath;
	});

	Vue.prototype.needRefresh = (route_name, callback) => {
		//console.log(url_map[route_name].old_path, url_map[route_name].new_path);
		if(url_map[route_name].old_path != "" && url_map[route_name].new_path != url_map[route_name].old_path) { // 如果新的路径不等于老的路径，说明应该刷新
			callback.call(this);
		}
		url_map[route_name].old_path = url_map[route_name].new_path;
	}

	
	// ***用于保证异步下的执行顺序*************************************************************************************
	Vue.prototype.process = process;
}

function addApiCacheData(hash, obj) {
	var apiCacheData;

	try {
		apiCacheData = JSON.parse(localStorage.apiCacheData || "{}");
	}catch(err) {
		apiCacheData = {};
	}

	apiCacheData[hash] = {
		time: Date.now(), 
		data: obj
	};

	try {
		localStorage.apiCacheData = JSON.stringify(apiCacheData);
	}catch(err) {
		localStorage.clear();
	}
}

function getApiCacheData(hash) {
	var apiCacheData;

	if(!localStorage.apiCacheData) {
		return null;
	}

	try {
		apiCacheData = JSON.parse(localStorage.apiCacheData);
		if(!apiCacheData[hash]) {
			return null;
		}else if(apiCacheData[hash].time + 5*60*1000 < Date.now()) { // 过期的数据
			return null;
		}else {
			return apiCacheData[hash].data;
		}
	}catch(err) {
		return null;
	}
}